// miniprogram/pages/show/detailed/detailed.js
const db = wx.cloud.database()
const substance = db.collection('substance')
const user = db.collection('user')
const star = db.collection('star')
const commentdata = db.collection('comment')
const _ = db.command
Page({

  /**
   * 页面的初始数据
   */
  data: {
    starcolor:'888888',
    starT:'关注',
    columnsBook: ['计算机', '机电', '自动化', '轻化', '信工', '土木与交通', '管理', '材能', '环境', '外国语', '应数', '物理', '艺设', '政法', '建筑城规', '经贸', '生物医学', '国际教育'],
    columnsGood: ['电子产品', '体育用品', '生活用品', '其他'],
    goodList: null,
    freelist: null,
    userList:null,
    userInfo: {
      avatarUrl: null,
      nickName: null
    },
    commentValue:null,
    commentlist:null
  },
  ifStart:function(){
    let self = this;
    if(self.data.starcolor=='888888'){
      wx.getStorage({
        key: 'detailid',
        success: function (res) {
          let thisid = res.data
          substance.where({
            _id: thisid
          }).get({
            success: res => {
              console.log(res)
          star.add({
            data: {
              starid: thisid,
              staropenid: res.data[0].openid,
              data: res.data[0].data,
              name: res.data[0].name,
                tip: res.data[0].tip,
                type: res.data[0].type,
                username: res.data[0].username,
                userpic: res.data[0].userpic,
              fileID: res.data[0].fileID,
            }, success(res) {
              self.setData({
                starcolor: 'FFCC00',
                starT: '不再关注'
              })
            },
            fail: console.error
          })
          }
          })
        }
      })
    }else{
      wx.getStorage({
        key: 'openid',
        success: function (res) {
          let openid=res.data
          wx.getStorage({
            key: 'detailid',
            success: function (res) {
              star.where({
                _openid: openid,
                starid: res.data 
              }).get({
                success: res=>{
                  console.log(res.data[0]._id)
                  star.doc(res.data[0]._id).remove({
                    success(res) {
                      
                      self.setData({
                        starcolor: '888888',
                        starT: '关注'
                      })
                    }
                  })
                  
                }
              })
            }
          })
      }  
      })
    }
  },
  handleCommentInput:function(e){
    let self=this;
    self.setData({
      commentValue: e.detail.value
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  copyQQ:function(e){
    console.log(e);
    var that = this;
    wx.setClipboardData({
      //准备复制的数据
      data: that.data.userList.qqNum,
      success: function (res) {
        wx.showToast({
          title: '复制成功',
        });
      }
    });
  },
  copyTel: function (e) {
    console.log(e);
    var that = this;
    wx.setClipboardData({
      //准备复制的数据
      data: that.data.userList.wxNum,
      success: function (res) {
        wx.showToast({
          title: '复制成功',
        });
      }
    });
  },
  onLoad: function (params) {
    let self=this
    wx.getSetting({
      success: res => {
        wx.getUserInfo({
          success: res => {
            this.setData({
              userInfo: {
                avatarUrl: res.userInfo.avatarUrl,
                nickName: res.userInfo.nickName
              }
            })
          }
        })
      }
    })
    this.getDetail(params._id, params._openid)
  },
  getDetail(_id, _openid) {
    let self = this;
    wx.getStorage({
      key: 'openid',
      success: function (res) {
        star.where({
          _openid: res.data,
          starid: _id
        }).get({
          success: res => {
            console.log(res.data.length)
            if(res.data.length){
              self.setData({
                starcolor: 'FFCC00',
                starT: '不再关注'
              })
            }
          }
        })
      }
    })
    console.log(_id)
    wx.setStorage({
      key: 'detailid',
      data: _id
    })
    wx.setStorage({
      key: 'detailopenid',
      data: _openid
    })
    commentdata.where({
      articles:_id
    }).get({
      success: res => {
        let commentlist = res.data
        let handleTime = (date) => {
          let nowTime = (new Date()).valueOf()
          if (parseInt((nowTime - date) / 2592000000) >= 1) {
            return parseInt((nowTime - date) / 2592000000) + '月前'
          } else if (parseInt((nowTime - date) / 86400000) >= 1) {
            return parseInt((nowTime - date) / 86400000) + '天前'
          } else if (parseInt((nowTime - date) / 3600000) >= 1) {
            return parseInt((nowTime - date) / 3600000) + '小时前'
          } else if (parseInt((nowTime - date) / 60000) >= 1) {
            return parseInt((nowTime - date) / 60000) + '分钟前'
          } else {
            return '刚刚'
          }
        }
        for (let i = 0; i < commentlist.length; i++) {
          commentlist[i].date = handleTime(commentlist[i].date)
        }
        // res.data 是包含以上定义的两条记录的数组
         self.setData({
           commentlist: commentlist
        })
      }
    })
    user.where({
      _openid:_openid
    }).get({
      success: res => {
        self.setData({
          userList: res.data[0]
        })
        if (wx.getStorageSync("ifBind")) {
        } else {
          let wxNum = "userList.wxNum"
          let qqNum = "userList.qqNum"
          let hiddenwx = self.hidden(self.data.userList.wxNum, 1, 1)
          let hiddenqq = self.hidden(self.data.userList.qqNum, 1, 1)
          self.setData({
            [wxNum]: hiddenwx,
            [qqNum]: hiddenqq
          })
        }
      }
    })
    substance.where({
      _id:_id
    }).get({
      success: res => {
        let goodList = res.data
        let handleTime = (date) => {
          let nowTime = (new Date()).valueOf()
          if (parseInt((nowTime - date) / 2592000000) >= 1) {
            return parseInt((nowTime - date) / 2592000000) + '月前'
          } else if (parseInt((nowTime - date) / 86400000) >= 1) {
            return parseInt((nowTime - date) / 86400000) + '天前'
          } else if (parseInt((nowTime - date) / 3600000) >= 1) {
            return parseInt((nowTime - date) / 3600000) + '小时前'
          } else if (parseInt((nowTime - date) / 60000) >= 1) {
            return parseInt((nowTime - date) / 60000) + '分钟前'
          } else {
            return '刚刚'
          }
        }
        for (let i = 0; i < goodList.length; i++) {
          wx.cloud.downloadFile({
            fileID: goodList[i].fileID, // 文件 ID
            success: res => {
              // 返回临时文件路径
              goodList[i].fileID = res.tempFilePath
            },
            fail: console.error
          })
          if (goodList[i].tip == 'good') {
            goodList[i].type = self.data.columnsGood[goodList[i].type];
          } else {
            goodList[i].type = self.data.columnsBook[goodList[i].type];
          }
          goodList[i].date = handleTime(goodList[i].date)
        }
        // res.data 是包含以上定义的两条记录的数组
        self.setData({
          goodList: res.data[0]
        })
      }
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  tobind:function(){
    wx.redirectTo({
      url: '../../../pages/me/bind/bind'
    })
  },
  onReady: function () {
  },
  handlePreview() {
    wx.previewImage({
      current: '1',
      urls: [this.data.goodList.fileID]
    })
  },
  uploadCom: function (){
    let self = this;
    if (self.data.commentValue){
      wx.showLoading({
        title: '上传评论中...',
        mask: true
      })
      db.collection('comment').add({
        data: {
          username: self.data.userInfo.nickName,
          userpic: self.data.userInfo.avatarUrl,
          articles: self.data.goodList._id,
          date: (new Date()).valueOf(),
          comment: self.data.commentValue,
        }
      }).then(
        wx.getStorage({
          key: 'detailid',
          success(res) {
            commentdata.where({
              articles: res.data
            }).get({
              success: res => {
                let commentlistS = res.data
                let handleTime = (date) => {
                  let nowTime = (new Date()).valueOf()
                  console.log(nowTime + "YU" + date + "deng" +((parseInt(nowTime) - parseInt(date))))
                  if (parseInt(nowTime - date)<60000){
                    return '刚刚'
                  }else if (parseInt((nowTime - date) / 2592000000) >= 1) {
                    return parseInt((nowTime - date) / 2592000000) + '月前'
                  } else if (parseInt((nowTime - date) / 86400000) >= 1) {
                    return parseInt((nowTime - date) / 86400000) + '天前'
                  } else if (parseInt((nowTime - date) / 3600000) >= 1) {
                    return parseInt((nowTime - date) / 3600000) + '小时前'
                  } else if (parseInt((nowTime - date) / 60000) >= 1) {
                    return parseInt((nowTime - date) / 60000) + '分钟前'
                  } else {
                    return '刚刚'
                  }
                }
                for (let i = 0; i < commentlistS.length; i++) {
                  commentlistS[i].date = handleTime(commentlistS[i].date)
                }
                // res.data 是包含以上定义的两条记录的数组
                self.setData({
                  commentlist: commentlistS,
                  commentValue:null,
                })
                wx.hideLoading()
              }
            })
          }
        }),
      )
    }else{
      wx.showModal({
        title: '提示',
        showCancel: false,
        content: '评论不能为空',
      })
    }
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
  
  },
  hidden(str, frontLen, endLen) {
    var len = str.length - frontLen - endLen;
    var xing = '';
    for (var i = 0; i < len; i++) {
      xing += '*';
    }
    return str.substring(0, frontLen) + xing + str.substring(str.length - endLen);
  },
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})